<?php

namespace Admin\Models\user;

use Admin\Models\BaseModel;
use Helpers\Main;
use Helpers\UserPower;
use Admin\Models\sys\XhsysPower;
use Modules\Power;

class XhsysUserpower extends BaseModel
{

    /**
     *
     * @var integer
     */
    public $iUPowerId;

    /**
     *
     * @var integer
     */
    public $iUPUserId;

    /**
     *
     * @var string
     */
    public $sUPowerValue;

    /**
     *
     * @var string
     */
    public $mUPowerTag;

    /**
     *
     * @var string
     */
    public $sUExtraView;

    /**
     *
     * @var string
     */
    public $sUExtraManage;

    /**
     *
     * @var integer
     */
    public $bDelete;

    /**
     *
     * @var string
     */
    public $tCreateDate;

    /**
     *
     * @var string
     */
    public $iCreateUserId;

    /**
     *
     * @var string
     */
    public $tLastModifyDate;

    /**
     *
     * @var string
     */
    public $iLastModifyUserId;

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        parent::initialize();
        $this->setSource("XHSys_UserPower");
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'XHSys_UserPower';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhsysUserpower[]
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhsysUserpower
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    /**
     * 根据用户及权限值添加记录
     *
     * @param $userId
     * @param $powerTags
     * @return XhsysUserpower
     *
     * create by ck 20160826
     * modify by ck 20170405    创建由value改为tag
     */
    public static function createRecord($userId, $powerTags)
    {
        $userPower = self::findFirst([
            'conditions' => 'bDelete = 0 AND iUPUserId = :userId:',
            'bind'       => ['userId' => $userId]
        ]);
        if(!$userPower) {
            $userPower = new self;
            $userPower->iUPUserId = $userId;
        }
        $userPower->mUPowerTag = $powerTags;
        return $userPower->save();
    }

    /**
     * 设置扩展权限，以json方式储存
     *
     * @param $userId               --用户ID
     * @param $target               --目标权限
     * @param array $viewPower      --列表权限
     * @param array $managePower    --管理权限
     * @return bool
     *
     * create by ck 20160907
     * modify by ck 20170417    优化
     */
    public static function createExtraRecord($userId, $target, $viewPower = array(), $managePower = array())
    {
        $userPower = self::findFirst('bDelete = 0 AND iUPUserId = '. $userId);
        if(!$userPower)
        {
            $userPower = new self;
            $userPower->iUPUserId = $userId;
            if(!empty($viewPower)) $userPower->sUExtraView = json_encode(array($target => $viewPower));
            if(!empty($managePower)) $userPower->sUExtraManage = json_encode(array($target => $managePower));
            return $userPower->insertData();
        }
        $extraView   = json_decode($userPower->sUExtraView, true);
        $extraManage = json_decode($userPower->sUExtraManage, true);
//        if(!empty($viewPower)) foreach($viewPower as $key => $value) if(!empty($value)) $extraView[$target][$key] = $value;
//        if(!empty($managePower)) foreach($managePower as $key => $value) if(!empty($value)) $extraManage[$target][$key] = $value;
        foreach($viewPower as $key => $value){
            $extraView[$target][$key] = $value;
        }
        foreach($managePower as $key => $value){
            $extraManage[$target][$key] = $value;
        }
        $userPower->sUExtraView     = json_encode($extraView, JSON_UNESCAPED_UNICODE);
        $userPower->sUExtraManage   = json_encode($extraManage, JSON_UNESCAPED_UNICODE);
        return $userPower->updateData();
    }

    /**
     * 检查用户是否有此权限
     * 分配权限时检查是否已有
     *
     * @param $userId
     * @param $powerValue
     * @return bool
     *
     * create by ck 20160830
     */
//    public static function checkUserPowerByValue($userId, $powerValue)
//    {
//        static $powerArr, $flag = false;
//        if(!$flag){
//            $powerArr = XhsysUserpower::findFirst("iUPUserId = {$userId}")->sUPowerValue;
//            $powerArr = explode(',', $powerArr);
//            $flag = true;
//        }
//        return in_array($powerValue, $powerArr) ? true : false;
//    }

    /**
     * 根据权限标识判断用户是否有权限
     *
     * @param $userId
     * @param $powerTag
     * @param $view
     * @return bool
     *
     * create by ck 20170405
     */
//    public static function checkUserPowerByTag($userId, $powerTag, $view = false)
//    {
//        static $powerArr, $flag = false;
//        if(!$flag){
//            if ($view) {
//                $powerArr = UserPower::getUserPowerTags($userId);
//            }
//            else {
//                $powerArr = XhsysUserpower::findFirst("iUPUserId = {$userId}")->mUPowerTag;
//                $powerArr = explode(',', $powerArr);
//            }
//            $flag = true;
//        }
//        return in_array($powerTag, $powerArr) ? true : false;
//    }

    /**
     * 根据节点ID，获取session中当前用户ID
     * 根据信息查找用户有权限的节点，如果当前节点有权限返回true，否则返回false
     *
     * @param $nodeId
     * @return bool
     *
     * create by ck 20160914
     * modify by ck 20170405    根据tag判断
     */
    public static function checkUserPowerByNode($nodeId)
    {
        static $nodeArr, $logonName;
        if ($logonName == 'admin') return true;
        if(!$logonName){
            $logonName = strtolower(Main::getLoginUserInfo('logonName'));
            if($logonName == 'admin') return true;
//            $userId = Main::getLoginUserInfo('userId');
//            $userPower = XhsysUserpower::findFirst("iUPUserId = {$userId}");
//            if(!$userPower) return false;
//            $powerTags = $userPower->mUPowerTag;
//            if(!$powerTags) return false;
//            $powerTags = explode(',', $powerTags);
//            $powerTags = UserPower::getUserPowerTags();
            $powerTags = Power::getPowerTags();
            if (!$powerTags) {
                $nodeArr = [];
            }
            else {
                $nodeArr = XhsysPower::find(array(
                    'columns'    => 'iNodeId',
                    'conditions' => "bPowerMain = 1 AND sPowerTag IN ({tagArr:array})",
                    'bind'       => ['tagArr' => $powerTags]
                ))->toArray();
                $nodeArr = array_column($nodeArr, 'iNodeId');
            }
        }
        return in_array($nodeId, $nodeArr) ? true : false;
    }


}
